package com.campus.help.controller;

import com.campus.help.dto.ApiResponse;
import com.campus.help.dto.TaskPublishRequest;
import com.campus.help.entity.Task;
import com.campus.help.enums.TaskStatus;
import com.campus.help.service.TaskService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/tasks")
@RequiredArgsConstructor
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class TaskController {
    
    private final TaskService taskService;
    
    /**
     * 发布任务
     * @param request 任务发布请求
     * @param publisherId 发布者学号（实际项目中应从认证信息获取）
     * @return 发布结果
     */
    @PostMapping(value = "/publish", produces = "application/json;charset=UTF-8")
    public ApiResponse<String> publishTask(@Valid @RequestBody TaskPublishRequest request,
                                          @RequestHeader("Publisher-Id") String publisherId) {
        try {
            String result = taskService.publishTask(request, publisherId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 接受任务
     * @param taskId 任务ID
     * @param acceptorId 接受者学号（实际项目中应从认证信息获取）
     * @return 接受结果
     */
    @PostMapping(value = "/{taskId}/accept", produces = "application/json;charset=UTF-8")
    public ApiResponse<String> acceptTask(@PathVariable String taskId,
                                         @RequestHeader("Acceptor-Id") String acceptorId) {
        try {
            String result = taskService.acceptTask(taskId, acceptorId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 完成任务
     * @param taskId 任务ID
     * @param userId 用户学号
     * @return 完成结果
     */
    @PostMapping(value = "/{taskId}/complete", produces = "application/json;charset=UTF-8")
    public ApiResponse<String> completeTask(@PathVariable String taskId,
                                           @RequestHeader("User-Id") String userId) {
        try {
            String result = taskService.completeTask(taskId, userId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取所有任务列表
     * @return 任务列表
     */
    @GetMapping(value = "/list", produces = "application/json;charset=UTF-8")
    public ApiResponse<List<Task>> getAllTasks() {
        List<Task> tasks = taskService.getAllTasks();
        return ApiResponse.success(tasks);
    }
    
    /**
     * 根据状态获取任务列表
     * @param status 任务状态
     * @return 任务列表
     */
    @GetMapping(value = "/list/status/{status}", produces = "application/json;charset=UTF-8")
    public ApiResponse<List<Task>> getTasksByStatus(@PathVariable TaskStatus status) {
        List<Task> tasks = taskService.getTasksByStatus(status);
        return ApiResponse.success(tasks);
    }
    
    /**
     * 获取待接受的任务列表
     * @return 任务列表
     */
    @GetMapping(value = "/list/pending", produces = "application/json;charset=UTF-8")
    public ApiResponse<List<Task>> getPendingTasks() {
        List<Task> tasks = taskService.getTasksByStatus(TaskStatus.PENDING);
        return ApiResponse.success(tasks);
    }
    
    /**
     * 获取用户发布的任务
     * @param publisherId 发布者学号
     * @return 任务列表
     */
    @GetMapping(value = "/list/publisher/{publisherId}", produces = "application/json;charset=UTF-8")
    public ApiResponse<List<Task>> getTasksByPublisher(@PathVariable String publisherId) {
        List<Task> tasks = taskService.getTasksByPublisher(publisherId);
        return ApiResponse.success(tasks);
    }
    
    /**
     * 获取用户接受的任务
     * @param acceptorId 接受者学号
     * @return 任务列表
     */
    @GetMapping(value = "/list/acceptor/{acceptorId}", produces = "application/json;charset=UTF-8")
    public ApiResponse<List<Task>> getTasksByAcceptor(@PathVariable String acceptorId) {
        List<Task> tasks = taskService.getTasksByAcceptor(acceptorId);
        return ApiResponse.success(tasks);
    }
    
    /**
     * 获取任务详情
     * @param taskId 任务ID
     * @return 任务详情
     */
    @GetMapping(value = "/{taskId}", produces = "application/json;charset=UTF-8")
    public ApiResponse<Task> getTaskById(@PathVariable String taskId) {
        Optional<Task> taskOpt = taskService.getTaskById(taskId);
        if (taskOpt.isPresent()) {
            return ApiResponse.success(taskOpt.get());
        } else {
            return ApiResponse.error("任务不存在");
        }
    }
    
    /**
     * 放弃任务
     * @param taskId 任务ID
     * @param acceptorId 接受者学号
     * @return 放弃结果
     */
    @PostMapping(value = "/{taskId}/abandon", produces = "application/json;charset=UTF-8")
    public ApiResponse<String> abandonTask(@PathVariable String taskId,
                                           @RequestHeader("Acceptor-Id") String acceptorId) {
        try {
            String result = taskService.abandonTask(taskId, acceptorId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 撤回任务
     * @param taskId 任务ID
     * @param publisherId 发布者学号
     * @return 撤回结果
     */
    @PostMapping(value = "/{taskId}/withdraw", produces = "application/json;charset=UTF-8")
    public ApiResponse<String> withdrawTask(@PathVariable String taskId,
                                            @RequestHeader("Publisher-Id") String publisherId) {
        try {
            String result = taskService.withdrawTask(taskId, publisherId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 修改任务（仅发布者）
     */
    @PostMapping(value = "/{taskId}/update", produces = "application/json;charset=UTF-8")
    public ApiResponse<String> updateTask(@PathVariable String taskId,
                                          @RequestHeader("Publisher-Id") String publisherId,
                                          @RequestBody TaskPublishRequest request) {
        try {
            String result = taskService.updateTask(taskId, publisherId, request);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}